package com.example.plant;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;


public class BaseApplication extends Application{
    private static Context sContext;
    private static Toast mAppToast;
    private final static int MSG_SHOW_APPLICATION_TOAST = 1000;
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        sContext = this.getApplicationContext();
    }
     
    public static Handler getBaseHandler() {
        return mHandler;
    }
    
    public static Context getContext() {
        return sContext;
    }
    
    private static Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case MSG_SHOW_APPLICATION_TOAST:
                if (mAppToast == null) {
                    mAppToast = Toast.makeText(sContext, String.valueOf(msg.obj), Toast.LENGTH_SHORT);
                    mAppToast.show();
                } else {
                    mAppToast.setText(String.valueOf(msg.obj));
                    // mAppToast.cancel();
                    mAppToast.show();
                }
                break;

            default:
                break;
            }
        };
    };

    /**
     * Convenient for showing Toast message throughout application.
     * @param msg message want to show.
     */
    public static void makeToastMsg(String msg) {
        Message msgs = mHandler.obtainMessage(MSG_SHOW_APPLICATION_TOAST, msg);
        mHandler.sendMessage(msgs);
    }
    
    public static void hideKeyboard(Activity activity, View viewToken){
        if(activity == null || viewToken == null) return;
        InputMethodManager imm = (InputMethodManager)activity.getSystemService(
                Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(viewToken.getWindowToken(), 0);
          activity.getWindow().setSoftInputMode(
                  WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
    
    public static void showKeyboard(Activity activity, View viewToken){
        if(activity == null || viewToken == null) return;
        InputMethodManager imm = (InputMethodManager)activity.getSystemService(
                Context.INPUT_METHOD_SERVICE);
          imm.showSoftInput(viewToken, 0);
          activity.getWindow().setSoftInputMode(
                  WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
